package com.example.sunmiv1.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.DeliveryGoodsAdapter;
import com.example.sunmiv1.adapter.DeliveryTypeAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.DeliveryTypeBean;
import com.example.sunmiv1.entity.OrderDetailInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeliveryGoodsActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.delivery_chooseGoods)
    ImageView deliveryChooseGoods;
    @BindView(R.id.delivery_chooseType)
    ImageView deliveryChooseType;
    @BindView(R.id.delivery_commit)
    ImageView deliveryCommit;
    @BindView(R.id.delivery_chooseGoodsTv)
    TextView deliveryChooseGoodsTv;
    @BindView(R.id.delivery_chooseTypeTv)
    TextView deliveryChooseTypeTv;
    @BindView(R.id.delivery_commitTv)
    TextView deliveryCommitTv;
    @BindView(R.id.delivery_listView)
    ListView deliveryListView;
    @BindView(R.id.delivery_next)
    TextView deliveryNext;
    @BindView(R.id.delivery_lastStep)
    TextView deliveryLastStep;
    @BindView(R.id.delivery_submit)
    TextView deliverySubmit;
    @BindView(R.id.delivery_lastAndSubmit)
    LinearLayout deliveryLastAndSubmit;
    @BindView(R.id.delivery_deliveryList)
    ListView deliveryDeliveryList;
    @BindView(R.id.delivery_deliveryBack)
    TextView deliveryDeliveryBack;
    @BindView(R.id.delivery_deliveryComplete)
    LinearLayout deliveryDeliveryComplete;
    @BindView(R.id.delivery_schedule)
    LinearLayout deliverySchedule;
    @BindView(R.id.UuDelivery_info)
    TextView UuDeliveryInfo;
    @BindView(R.id.UuDelivery_phone)
    EditText UuDeliveryPhone;
    @BindView(R.id.UuDelivery_need)
    RadioButton UuDeliveryNeed;
    @BindView(R.id.UuDelivery_noNeed)
    RadioButton UuDeliveryNoNeed;
    @BindView(R.id.UuDelivery_content)
    EditText UuDeliveryContent;
    @BindView(R.id.UuDelivery_cancel)
    TextView UuDeliveryCancel;
    @BindView(R.id.UuDelivery_sure)
    TextView UuDeliverySure;
    @BindView(R.id.UuDelivery_linear)
    LinearLayout UuDeliveryLinear;
    @BindView(R.id.makeDelivery_price)
    TextView MakeDeliveryPrice;
    @BindView(R.id.makeDelivery_distance)
    TextView MakeDeliveryDistance;
    @BindView(R.id.makeDelivery_phone)
    EditText MakeDeliveryPhone;
    @BindView(R.id.makeDelivery_content)
    EditText MakeDeliveryContent;
    @BindView(R.id.makeDelivery_cancel)
    TextView MakeDeliveryCancel;
    @BindView(R.id.makeDelivery_sure)
    TextView MakeDeliverySure;
    @BindView(R.id.makeDelivery_linear)
    LinearLayout MakeDeliveryLinear;

    private Context context;
    private LoadingDialog loadingDialog;

    private int flag = 1;//1確認配送商品 2選擇配送方式 3提交成功
    private List<OrderDetailInfo.DataBean> goodsList = new ArrayList<>();
    private DeliveryGoodsAdapter deliveryGoodsAdapter;
    private OrderDetailInfo orderDetailInfo;

    private DeliveryTypeBean deliveryTypeBean;
    private List<DeliveryTypeBean> deliveryList = new ArrayList<>();
    private DeliveryTypeAdapter deliveryTypeAdapter;
    private int deliveryType = 0;//0商家配送 1達達配送 2UU配送 3碼科配送

    @Override
    protected void initView() {
        setContentView(R.layout.activity_delivery_goods);
        ButterKnife.bind(this);
        context = this;
        loadingDialog = new LoadingDialog(context);
    }

    @Override
    protected void initData() {
        change();
        deliveryList.add(new DeliveryTypeBean(R.mipmap.shop_delivery, "商家配送", true));
        deliveryList.add(new DeliveryTypeBean(R.mipmap.dada_delivery, "達達配送", false));
        deliveryList.add(new DeliveryTypeBean(R.mipmap.uu_delivery, "UU配送", false));
        deliveryList.add(new DeliveryTypeBean(R.mipmap.make_delivery, "碼科配送", false));
        setDeliveryTypeAdapter();
    }

    @Override
    protected void initListener() {
        deliveryDeliveryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                deliveryType = position;
                for (DeliveryTypeBean bean : deliveryList) {
                    bean.setCheck(false);
                }
                deliveryList.get(position).setCheck(true);
                setDeliveryTypeAdapter();
            }
        });
    }

    private void setDeliveryGoodsAdapter() {
        if (deliveryGoodsAdapter == null) {
            deliveryGoodsAdapter = new DeliveryGoodsAdapter(goodsList);
            deliveryListView.setAdapter(deliveryGoodsAdapter);
        } else {
            deliveryGoodsAdapter.notifyDataSetChanged();
        }
        deliveryGoodsAdapter.setChoose(index -> {
            Intent intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 27);
            intent.putExtra("good", goodsList.get(index));
            startActivityForResult(intent, 200);
        });
    }

    private void setDeliveryTypeAdapter() {
        if (deliveryTypeAdapter == null) {
            deliveryTypeAdapter = new DeliveryTypeAdapter(deliveryList);
            deliveryDeliveryList.setAdapter(deliveryTypeAdapter);
        } else {
            deliveryTypeAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.title_back, R.id.delivery_next, R.id.delivery_lastStep, R.id.delivery_submit, R.id.delivery_deliveryBack,
    R.id.UuDelivery_sure,R.id.UuDelivery_cancel,R.id.UuDelivery_linear,R.id.makeDelivery_cancel,R.id.makeDelivery_sure,R.id.makeDelivery_linear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.delivery_next:
                if (flag == 1) {
                    for (OrderDetailInfo.DataBean bean : goodsList) {
                        if ("1".equals(bean.getSerial_number_state()) && (bean.getSerial_list().size() == 0 || bean.getNum() != bean.getSerial_list().size())) {
                            if (TextUtils.isEmpty(bean.getSku_name())) {
                                Toast.makeText(context, "請先選擇" + bean.getGoods_name() + "的串碼", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context, "請先選擇" + bean.getGoods_name() + "(" + bean.getSku_name() + ")" + "的串碼", Toast.LENGTH_SHORT).show();
                            }
                            return;
                        }
                    }
                }
                if ("1".equals(getIntent().getStringExtra("pickupType"))) {//自提
                    verGoods();
                } else {
                    flag++;
                    change();
                }
                break;
            case R.id.delivery_lastStep:
                flag--;
                change();
                break;
            case R.id.delivery_submit:
                verGoods();
                break;
            case R.id.delivery_deliveryBack:
                finish();
                break;
            case R.id.UuDelivery_linear:
                UuDeliveryLinear.setVisibility(View.GONE);
                break;
            case R.id.UuDelivery_cancel:
                UuDeliveryInfo.setText("");
                UuDeliveryPhone.setText("");
                UuDeliveryNoNeed.setChecked(true);
                UuDeliveryContent.setText("");
                UuDeliveryLinear.setVisibility(View.GONE);
                break;
            case R.id.UuDelivery_sure:
                deliveryGood();
                break;
            case R.id.makeDelivery_linear:
                MakeDeliveryLinear.setVisibility(View.GONE);
                break;
            case R.id.makeDelivery_cancel:
                MakeDeliveryDistance.setText("");
                MakeDeliveryPhone.setText("");
                MakeDeliveryPrice.setText("");
                MakeDeliveryContent.setText("");
                MakeDeliveryLinear.setVisibility(View.GONE);
                break;
            case R.id.makeDelivery_sure:
                deliveryGood();
                break;
        }
    }

    /**
     * 獲取訂單配送商品列表
     */
    private void getDetail() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_id", getIntent().getStringExtra("id"));
            HttpUtils.post(context, Common.SELL_LIST, Tools.createParameterCode(jsonObject), new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    orderDetailInfo = GsonUtils.JsonToBean(text, OrderDetailInfo.class);
                    if (orderDetailInfo.getStatus() == 1) {
                        goodsList.addAll(orderDetailInfo.getData());
                        setDeliveryGoodsAdapter();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void verGoods() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("goods_list", new Gson().toJson(goodsList));
            HttpUtils.post(context, Common.CONFIRM_DISTRIBUTION_GOODS, Tools.createParameterCode(jsonObject), new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            if ("1".equals(getIntent().getStringExtra("pickupType"))) {//自提
                                selfMention();
                            } else {
                                if (deliveryType==2){
                                    GetUuDeliveryInfo();
                                }else if (deliveryType==3){
                                    GetMakeDeliveryInfo();
                                }else {
                                    deliveryGood();
                                }
                            }
                        } else {
                            loadingDialog.dismiss();
                            if(json.has("msg")){
                                Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //獲取UU配送費*/
    private void GetUuDeliveryInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", getIntent().getStringExtra("orderNo"));
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_UU_DELIVERY_INFO, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        deliveryDeliveryList.setSelection(0);
                        UuDeliveryInfo.setText(json.getString("msg"));
                        UuDeliveryLinear.setVisibility(View.VISIBLE);
                    } else {
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 獲取碼科配送費
     */
    private void GetMakeDeliveryInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
           jsonObject.put("order_no", getIntent().getStringExtra("orderNo"));
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_MAKE_DELIVERY_INFO, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    JSONObject data = json.getJSONObject("data");
                    if (json.getInt("status") == 1) {
                        deliveryDeliveryList.setSelection(0);
                        MakeDeliveryDistance.setText(data.getString("distance"));
                        MakeDeliveryPrice.setText(data.getString("total_price"));
                        MakeDeliveryLinear.setVisibility(View.VISIBLE);
                    } else {
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

    /*自提*/
    private void selfMention() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", getIntent().getStringExtra("orderNo"));
            jsonObject.put("pick_code", getIntent().getStringExtra("pickupCode"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.SELF_MENTION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        if(json.has("msg")){
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                        }
                        if (json.getInt("status") == 1) {
                            flag = 3;
                            change();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void deliveryGood() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", getIntent().getStringExtra("orderNo"));
            jsonObject.put("type", deliveryType==3?5:deliveryType + 1);
            if (UuDeliveryNoNeed.isChecked()) {//不需要保溫箱
                jsonObject.put("special_type", 0);
            } else {
                jsonObject.put("special_type", 1);
            }
            if (deliveryType == 3) {
                jsonObject.put("total_price", MakeDeliveryPrice.getText().toString());
                jsonObject.put("distance", MakeDeliveryDistance.getText().toString());
            }
            jsonObject.put("uu_phone", UuDeliveryPhone.getText().toString());
            jsonObject.put("note", UuDeliveryContent.getText().toString());
            HttpUtils.post(context, Common.DELIVERY_ORDER_V2, Tools.createParameterCode(jsonObject), new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            flag++;
                            change();
                            UuDeliveryLinear.setVisibility(View.GONE);
                            MakeDeliveryLinear.setVisibility(View.GONE);
                        }
                        if (json.has("msg")) {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case 200:
                        OrderDetailInfo.DataBean bean = (OrderDetailInfo.DataBean) data.getSerializableExtra("bean");
                        int index = 0;
                        for (int t = 0; t < goodsList.size(); t++) {
                            if (bean.getGoods_id().equals(goodsList.get(t).getGoods_id())) {
                                if ("2".equals(bean.getAttribute_state())) {
                                    if (bean.getSku_id().equals(goodsList.get(t).getSku_id())) {
                                        index = t;
                                        break;
                                    }
                                } else {
                                    index = t;
                                    break;
                                }
                            }
                        }
                        goodsList.set(index, bean);
                        setDeliveryGoodsAdapter();
                        break;
                }
            }
        }
    }

    private void change() {
        deliveryChooseType.setImageResource(R.drawable.round_ffeff0);
        deliveryCommit.setImageResource(R.drawable.round_ffeff0);
        deliveryChooseTypeTv.setTextColor(ContextCompat.getColor(context, R.color.text_999));
        deliveryCommitTv.setTextColor(ContextCompat.getColor(context, R.color.text_999));
        switch (flag) {
            case 1:
                deliveryListView.setVisibility(View.VISIBLE);
                deliveryDeliveryList.setVisibility(View.GONE);
                deliveryLastAndSubmit.setVisibility(View.GONE);
                deliveryNext.setVisibility(View.VISIBLE);
                if (goodsList.size() == 0) {
                    getDetail();
                }
                if ("1".equals(getIntent().getStringExtra("pickupType"))) {//自提
                    deliveryDeliveryList.setVisibility(View.GONE);
                    deliverySchedule.setVisibility(View.GONE);
                    deliveryNext.setText("確定自提");
                }
                break;
            case 2:
                deliveryNext.setVisibility(View.GONE);
                deliveryLastAndSubmit.setVisibility(View.VISIBLE);
                deliveryChooseType.setImageResource(R.mipmap.round);
                deliveryChooseTypeTv.setTextColor(ContextCompat.getColor(context, R.color.text_333));
                deliveryListView.setVisibility(View.GONE);
                deliveryDeliveryList.setVisibility(View.VISIBLE);
                break;
            case 3:
                deliveryNext.setVisibility(View.GONE);
                deliveryLastAndSubmit.setVisibility(View.GONE);
                deliveryChooseType.setImageResource(R.mipmap.round);
                deliveryCommit.setImageResource(R.mipmap.round);
                deliveryListView.setVisibility(View.GONE);
                deliveryDeliveryList.setVisibility(View.GONE);
                deliveryDeliveryComplete.setVisibility(View.VISIBLE);
                deliveryChooseTypeTv.setTextColor(ContextCompat.getColor(context, R.color.text_333));
                deliveryCommitTv.setTextColor(ContextCompat.getColor(context, R.color.text_333));
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
